package com.ops.chirpit;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.Facebook;
import com.google.ads.Ad;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;


import fi.foyt.foursquare.api.FoursquareApi;

public class ChirpItActivity extends Activity {
	private static JSONArray images = new JSONArray();
    static Location location;  
    private String attachUrl = null;
    private static SharedPreferences prefs;
    static Map<String,?> prefMap;
	public static final String ACCOUNT_PREFS = "com.ops.chirpit.ACCOUNTS", PREFS_NAME = "com.ops.chirpit",  TAG = "ChirpIt";
	public static final AccountType[] accountTypes = AccountType.setAccountTypes();
	public static final int TWITTER = 0, FACEBOOK = 1, FOURSQUARE = 2, MYSPACE = 3, LINKEDIN = 4, GOOGLEPLUS = 5;
	static String[] attachPlace; 
	static ArrayList<String> deleteObjects = new ArrayList<String>();
    static JSONArray[] attachFriends;
	static final String FB_APP_ID = "165909040144120";
	public static Twitter twitter = new TwitterFactory().getInstance();
	public static Facebook authenticatedFacebook = new Facebook(FB_APP_ID);
	public static FoursquareApi foursquareApi = AuthActivity.foursquareApi();
	public static JSONArray accounts = new JSONArray();
	public static boolean[] checkedAccounts, tCheckedAccounts;
	boolean accountsChanged = true;
	static String locationListLength;
    static final int LOAD_ACCOUNTS = 0, PLACES = 1, FRIENDS = 2, MEDIA = 3, PREFERENCES = 4, PICK_ACCOUNTS = 5, ADD_ACCOUNT = 6, LINK = 7, SCHEDULE = 8;
    String[] title = {"Account Info", "Places", "Friends","Select Picture","Preferences","Select Accounts to Update"};
	static String[] imageAttachmentOptions = {"Choose from gallery", "Take with Camera"};
    static ProgressThread progressThread;
    static ProgressDialog progressDialog;
    Context mContext = this;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final EditText editPost = (EditText) findViewById(R.id.editPost);
		final TextView textResults = (TextView) findViewById(R.id.textResults);
		final TextView char_count = (TextView) findViewById(R.id.textStatusLength);		
		
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		locationListLength = sp.getString("locationListLength", "3");

		if(accounts.length() == 0){
			clearAccounts();
			showDialog(LOAD_ACCOUNTS);
		}
        
	    final TextWatcher tWatcher = new TextWatcher(){
			public void beforeTextChanged(CharSequence s, int start, int count, int after){
			}
			//@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
			//@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				char_count.setText(String.valueOf(s.length()));
			}
		};
		editPost.addTextChangedListener(tWatcher);
		
		((TextView) this.findViewById(R.id.textAccounts)).setOnClickListener(new OnClickListener() {
	    	public void onClick(View arg0) {
	    		if (accounts.length() > 0)
	    			showDialog(PICK_ACCOUNTS);
	    		else{
	    			clearAccounts();
	    			showDialog(LOAD_ACCOUNTS);
	    			showDialog(PICK_ACCOUNTS);
	    		}
	        }
	    });
	    
	    ((Button) this.findViewById(R.id.btnMedia)).setOnClickListener(new OnClickListener() {
	    	public void onClick(View arg0) {
	    		if(images.length() > 0)
	    			showDialog(MEDIA);
	    		else{
		            Intent intent = new Intent();
		            intent.setType("image/*");
		            intent.setAction(Intent.ACTION_GET_CONTENT);
		            startActivityForResult(Intent.createChooser(intent,
		                    "Select Picture"), MEDIA);
	    		}
	        }
	    });
	    
	    ((Button) this.findViewById(R.id.btnLocation)).setOnClickListener(new OnClickListener() {
	    	public void onClick(View arg0) {
	  	    	startActivityForResult(new Intent(ChirpItActivity.this, LocationActivity.class), PLACES);
	    	}
	    });
	    
	    ((Button) this.findViewById(R.id.btnMention)).setOnClickListener(new OnClickListener() {
	    	public void onClick(View arg0) {
	    		startActivityForResult(new Intent(ChirpItActivity.this, FriendActivity.class), FRIENDS);
	    	}
	    });
	    
	    ((Button) this.findViewById(R.id.btnLink)).setOnClickListener(new OnClickListener() {
	    	public void onClick(View arg0) {
	    		
	    		//Call bit.ly to shorten url
	    	    attachUrl = BitlyAndroid.shortenUrl(editPost.getText().toString());
	    	    editPost.setText("");
	    	    Toast.makeText(ChirpItActivity.this, "Attached link: " + attachUrl, Toast.LENGTH_LONG).show();
	    	    if (attachUrl != null)
	    	    	updateAttachmentButtons(LINK);
	    	}
	    });
	    
	    ((Button) this.findViewById(R.id.btnReset)).setOnClickListener(new OnClickListener() {
	    	public void onClick(View arg0) {
	    		clearEverything();
	    	}
	    });
	    
	    ((Button) this.findViewById(R.id.buttonSubmit)).setOnClickListener(new OnClickListener() {
	    	public void onClick(View arg0) {
	    		String status, message;  
	    		boolean twPost = false, fbPost = false, fsPost = false;
	    		
	    		status = editPost.getText().toString();
				for(int i = 0; i < checkedAccounts.length; i++){
					if(checkedAccounts[i]){
						try{
							JSONObject account = (JSONObject) accounts.get(i);
							String secret = (account.has("secret"))? account.getString("secret"): "";
							String token = account.getString("token");
							String id = account.getString("id");
							int network = account.getInt("network");
							switch(network){
							case TWITTER:
								twPost = UpdateHelper.updateTwitter(token, secret, status, location, images, attachPlace[0], attachUrl);
								break;
							case FACEBOOK:
								fbPost = UpdateHelper.updateFacebook(id, token, status, images, location, attachPlace[1], attachUrl);
								break;
							case FOURSQUARE:
								fsPost = UpdateHelper.updateFoursquare(token, status, images, location, attachPlace[2], attachUrl);
								break;
							}							
						}catch (Exception e){
	    	        		// TODO Auto-generated catch block
	    	        		e.printStackTrace();
						}
					}
				}		
				textResults.setText("Status update: " + status);
				editPost.setText("");
				message = "Updated: Twitter - " + twPost + " Facebook - " + fbPost + " Foursquare - " + fsPost;
	    		Toast.makeText(ChirpItActivity.this, message, Toast.LENGTH_LONG).show();
	        }
	    });
	    handleIntent(getIntent());
	    
	    LinearLayout adLayout = (LinearLayout) this.findViewById(R.id.adLayout);
	    AdView adView = new AdView(this, AdSize.IAB_BANNER, "adUnitId");
	    AdRequest adRequest = new AdRequest();
	    adLayout.addView(adView);
	    adView.loadAd(adRequest);
	    
	    for(int i = 0; i < 7; i++)
	    	updateAttachmentButtons(i);
	}
    
    public void handleIntent(Intent intent){
    	EditText editPost = (EditText) findViewById(R.id.editPost);
    	Bundle extras = intent.getExtras();
	    if (extras != null){
		    Set<String> set = extras.keySet();
		    set.size();
	    }
	    String action = intent.getAction();

	    // if this is from the share menu
	    if (Intent.ACTION_SEND.equals(action))
	    {
	        if (extras.containsKey(Intent.EXTRA_STREAM))
	        {
	            try
	            {
		        	String selectedImagePath;
		        	String filemanagerstring;
	                // Get resource path from intent called
	                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
	                //OI FILE Manager
		            filemanagerstring = uri.getPath();
		            //MEDIA GALLERY
		            selectedImagePath = getPath(uri);
		            selectedImagePath = (selectedImagePath == null)? filemanagerstring: selectedImagePath;
			    	images.put(selectedImagePath);
	                return;
	            } catch (Exception e)
	            {
	                Log.e(this.getClass().getName(), e.toString());
	            }

	        } else if (extras.containsKey(Intent.EXTRA_TEXT))
	        {
	        	editPost.setText(extras.getString(Intent.EXTRA_TEXT).toString());
	            return;
	        }
	    }
    }
    
    public void updateAttachmentButtons(int requestCode){
    	String text = "";
    	int badgeText = 0;    	
    	switch(requestCode){ 
        case MEDIA:
	        badgeText = R.id.badgeTextMedia;
        	if(images.length() > 0){
	        	text = Integer.toString(images.length());	        	
        	}
            break;
        case PLACES:
        	int p = 0;
	        badgeText = R.id.badgeTextLocation;
        	if(attachPlace != null){
	        	for(String aP : attachPlace){
	        		if(aP != null)
	        			p++;
	        	}
        	}
        	if(p > 0){
	        	text = Integer.toString(p);
        	}
      	  	break;
        case FRIENDS:
        	int f = 0;
	        badgeText = R.id.badgeTextMention;
        	for(int i = 0; i < attachFriends.length; i++){
        		f += attachFriends[i].length();
        	}
        	if(f > 0){
	        	text = Integer.toString(f);
        	}
      	  	break;
        case LINK:
	        badgeText = R.id.badgeTextLink;
        	if(attachUrl.length() > 0){
	        	text = "1";
        	}
      	  	break;
        }
    	if(badgeText > 0){
    		TextView tv = (TextView) findViewById(badgeText);
	    	if(text != "0" && text != ""){
	    		tv.setVisibility(View.VISIBLE);
	    		tv.setText(text);
	    	}else
	    		tv.setVisibility(View.INVISIBLE);	    		
    	}
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.add_account:
			addAccountDialog(ADD_ACCOUNT);
			break;
		case R.id.settings:
			// Launch Preference activity
			startActivityForResult(new Intent(ChirpItActivity.this, Preferences.class), PREFERENCES);
			// Some feedback to the user
			Toast.makeText(this, "Just a test", Toast.LENGTH_LONG).show();
			break;
		}
		return true;
	}
	//UPDATED
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	      if (resultCode == RESULT_OK) {
	          switch(requestCode) {
	          case MEDIA:
	        	  String selectedImagePath, filemanagerstring;
	        	  Uri selectedImageUri = data.getData();
	              //Handle Media Gallery vs FileManager result
	              filemanagerstring = selectedImageUri.getPath();
	              selectedImagePath = getPath(selectedImageUri);
		    	  selectedImagePath = (selectedImagePath == null)? filemanagerstring: selectedImagePath;
		    	  String fileType = selectedImagePath.substring(selectedImagePath.lastIndexOf("."));
		    	  String[] imageArray = {selectedImagePath, fileType};
		    	  images.put(imageArray);
	              if(selectedImagePath!=null)
	            	  Toast.makeText(this, selectedImagePath, Toast.LENGTH_LONG).show();
	              break;
	          case PREFERENCES:
	        	  SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
	        	  locationListLength = sp.getString("locationListLength", "3");
	        	  break;
	          case ADD_ACCOUNT:
	        	  if (data.getExtras().getInt("ACTION") == ADD_ACCOUNT)
	        		clearAccounts();
	        	  	showDialog(LOAD_ACCOUNTS);
	        	  	return;
			case PLACES:
	        	  
	        	  break;
	          case FRIENDS:
	        	  
	        	  break;
	          case LINK:
	        	  
	        	  break;
	          }	          
	          updateAttachmentButtons(requestCode);
	      }
	  }
	  
	  //UPDATED!
	  public String getPath(Uri uri) {
	      String[] projection = { MediaStore.Images.Media.DATA };
	      Cursor cursor = managedQuery(uri, projection, null, null, null);
	      if(cursor!=null)
	      {
	          //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
	          //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
	          int column_index = cursor
	          .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	          cursor.moveToFirst();
	          return cursor.getString(column_index);
	      }
	      else return null;
	  }

    protected Dialog onCreateDialog(int id) {
    	Dialog dialog;
        switch(id) {
        case LOAD_ACCOUNTS:
            prefs = getSharedPreferences(ACCOUNT_PREFS, 0);
            prefMap = prefs.getAll();
            	/*
            }
            final Editor edit = prefs.edit();
    		  edit.clear();
            for(String pref : prefMap.keySet()){
            	if (pref.contains("fb_expiry")){
             		edit.remove(pref);
            	}
             edit.commit();
            }*/
        	break;
        case MEDIA:
        	JSONArray imageDialogObject = images;
        	/*for(String option: imageAttachmentOptions){
        		String[] attachmentInfo = {option, "action"};
        		imageDialogObject.put(attachmentInfo);
        	}*/
        	dialog = attachmentDialog(id, imageDialogObject);
        	dialog.setTitle(title[id]);
        	return dialog;
        case PLACES:
        	break;
        case FRIENDS:
        	break;
        case SCHEDULE:
        	break;
        case PICK_ACCOUNTS:
        	dialog = listAccountsDialog(id);
        	dialog.setTitle(title[id]);
        	return dialog;/*
        case ADD_ACCOUNT:
        	final CharSequence[] items = {"Twitter", "Facebook", "Foursquare"};

        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setTitle("Add an Account");
        	builder.setItems(items, new DialogInterface.OnClickListener() {
        	    public void onClick(DialogInterface dialog, int item) {
        	        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
        	    }
        	});
        	AlertDialog alert = builder.create();*/
        default:
        	return null;
        }
        progressDialog = new ProgressDialog(ChirpItActivity.this);
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {			
			public void onCancel(DialogInterface dialog) {
				clearAccounts();
			    showDialog(LOAD_ACCOUNTS);
			}
		});
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("Loading " + title[id] + "...");
        return progressDialog;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
    	deleteObjects = new ArrayList<String>();
    	switch(id) {
        case LOAD_ACCOUNTS:
            prefs = getSharedPreferences(ACCOUNT_PREFS, 0);
            prefMap = prefs.getAll();
            break;
        case PICK_ACCOUNTS:
        	tCheckedAccounts = checkedAccounts;
        	if (accountsChanged){
	        	ListView lv1 = (ListView) dialog.findViewById(R.id.cld_listView1);
	        	lv1.setAdapter(new DialogListAdapter(this, accounts, id));
	        	accountsChanged = false;
        	}
        	break;
    	}
    	if(dialog.getClass().getName().toString().equals("android.app.ProgressDialog")){
    			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    			progressDialog.setMessage("Loading " + title[id] + "...");
		        progressDialog.setProgress(0);
		        progressThread = new ProgressThread(handler, id);
		        progressThread.start();
	    }
    }
    // Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int total = msg.arg1, max = msg.arg2;
            progressDialog.setMax(max);
            progressDialog.setProgress(total);
            if (total >= max){
                dismissDialog(LOAD_ACCOUNTS);
                ((ProgressThread) progressThread).setState(ProgressThread.STATE_DONE);
                if(accounts.length()>0){
	                checkedAccounts = new boolean[accounts.length()];
	                checkedAccounts[0] = true;
	                accountsChanged = true;
                }else{
        			addAccountDialog(ADD_ACCOUNT);
        		}
            }
        }
    };
	  
	  public Dialog listAccountsDialog(int id){
		  if(checkedAccounts == null){
              checkedAccounts = new boolean[accounts.length()];
              checkedAccounts[0] = true;
		  }
		  tCheckedAccounts = new boolean[checkedAccounts.length];
		  tCheckedAccounts = checkedAccounts;
		  AlertDialog.Builder builder;
		  AlertDialog alertDialog;
		  LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		  View layout = inflater.inflate(R.layout.custom_list_dialog,
		                                 (ViewGroup) findViewById(R.id.cld_layout_root));
		  final ListView lv1 = (ListView) layout.findViewById(R.id.cld_listView1);
		  lv1.setAdapter(new DialogListAdapter(this, accounts, id));
		  builder = new AlertDialog.Builder(mContext);
		  builder.setView(layout)
		  	.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   checkedAccounts = tCheckedAccounts;
	        	   if(!deleteObjects.isEmpty())
	        		   deleteAccounts(deleteObjects);
	        	   deleteObjects.clear();
	               dialog.dismiss();
	           }
	       })
	       .setNeutralButton("Add", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   addAccountDialog(id);
	                dialog.cancel();
	           }
	       })
	       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	                dialog.cancel();
	           }
	       });
		  alertDialog = builder.create();
		  return alertDialog;
	  }
	  
	  public void addAccountDialog(int id){
			ListAdapter adapter = new ArrayAdapter<AccountType>(
			    ChirpItActivity.this,
			    android.R.layout.select_dialog_item,
			    android.R.id.text1,
			    accountTypes){
			        public View getView(int position, View convertView, ViewGroup parent) {
			            //User super class to create the View
			            View v = super.getView(position, convertView, parent);
			            TextView tv = (TextView)v.findViewById(android.R.id.text1);	
			            //Put the image on the TextView
			            tv.setCompoundDrawablesWithIntrinsicBounds(accountTypes[position].drawable, 0, 0, 0);	
			            //Add margin between image and text (support various screen densities)
			            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
			            tv.setCompoundDrawablePadding(dp5);
			            tv.setText(accountTypes[position].name);	
			            return v;
			        }
			    };
	
	
			new AlertDialog.Builder(this)
			    .setTitle("Select Account Type")
			    .setAdapter(adapter, new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int item) {
		            	 Intent intent = new Intent();
		            	 intent.setAction("ACTION_VIEW")
		            	 	.setClass(ChirpItActivity.this, AuthActivity.class)
		            	 	.setData(Uri.parse(accountTypes[item].name));
		            	 startActivityForResult(intent, ChirpItActivity.ADD_ACCOUNT);
			        }
			    }).show();
		  
	  }
	  
	  Dialog attachmentDialog(int id, JSONArray object){
		  AlertDialog.Builder builder;
		  AlertDialog alertDialog;
		  LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		  View layout = inflater.inflate(R.layout.custom_list_dialog,
		                                 (ViewGroup) findViewById(R.id.cld_layout_root));
		  final ListView lv1 = (ListView) layout.findViewById(R.id.cld_listView1);
		  lv1.setAdapter(new DialogListAdapter(this, object, id));
		  lv1.setOnItemClickListener(new OnItemClickListener() {
	      	//@Override
	      	public void onItemClick(AdapterView<?> arg0, View view,
	             int position, long id) {
	        	for(String option: imageAttachmentOptions){
	        		if(((String[]) lv1.getItemAtPosition(position))[0] == option){
			            Intent intent = new Intent();
			            intent.setType("image/*");
			            intent.setAction(Intent.ACTION_GET_CONTENT);
			            startActivityForResult(Intent.createChooser(intent,
			                    "Select Picture"), MEDIA);
	        		}	        			
	        	}
			}			  
		  });
		  builder = new AlertDialog.Builder(mContext);
		  builder.setView(layout)
		  	.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	try {
	        	   for(int i = 0; i < images.length(); i++){
	        		   for(String path : deleteObjects){
	        			   String[] imageArray = (String[])images.get(i);
							if(imageArray[0] == path){
								imageArray[0] = "";
								images.put(i, imageArray);
								updateAttachmentButtons(MEDIA);
							}
	        		   }	        			   
	        	   }
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	        		   
	               dialog.dismiss();
	           }
	       })/*
	       .setNeutralButton("Add", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   Intent intent = new Intent();
		            intent.setType("image/*");
		            intent.setAction(Intent.ACTION_GET_CONTENT);
		            startActivityForResult(Intent.createChooser(intent,
		                    "Select Picture"), MEDIA);
	           }
	       })*/
	       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	                dialog.cancel();
	           }
	       });
		  alertDialog = builder.create();
		  return alertDialog;
	  }
	  
	  public void deleteAccounts(ArrayList<String> ids){
	 		//SharedPreferences sharedPrefs = getSharedPreferences(PREFS_NAME, 0);
	 		final Editor edit = prefs.edit();
	 		for (String pref : prefMap.keySet()){
	 			for(String id: ids){
		 			if(pref.contains(id))
		 				edit.remove(pref);
	 			}
	 		}
	 		edit.commit();
	 		showDialog(LOAD_ACCOUNTS);
	  }
	  
	  public void clearAccounts(){
	        prefs = getSharedPreferences(ACCOUNT_PREFS, 0);
	        prefMap = prefs.getAll();
		  	accounts = new JSONArray();
			twitter = new TwitterFactory().getInstance();
			authenticatedFacebook = new Facebook(FB_APP_ID);
			foursquareApi = AuthActivity.foursquareApi(); 
	  }
	  
	  public void clearEverything(){
	  	clearAccounts();
		images = new JSONArray();
	    location = null;  
	    attachUrl = null;
		attachPlace = null;
	    attachFriends = null;
	    ((TextView) this.findViewById(R.id.badgeTextMedia)).setVisibility(View.INVISIBLE);
	    ((TextView) this.findViewById(R.id.badgeTextLocation)).setVisibility(View.INVISIBLE);
	    ((TextView) this.findViewById(R.id.badgeTextMention)).setVisibility(View.INVISIBLE);
	    ((TextView) this.findViewById(R.id.badgeTextLink)).setVisibility(View.INVISIBLE);
	    showDialog(LOAD_ACCOUNTS);
      }
}